/**
 * @file POPTest.as
   mxmlc -library-path+=coltware_airxlib_r2.swc -debug=true POPTest.as  -static-link-runtime-shared-libraries=true  && flashplayerdebugger POPTest.swf
   mxmlc  -library-path+=coltware_airxlib_r2.swc -debug=true -incremental=true -swf-version=11 +configname=air POPTest.as
   Starting java as: java.exe -Xmx384m -Dsun.io.useCanonCaches=false -Duser.language=en -Duser.region=US -Djava.util.Arrays.useLegacyMergeSort=true -Dapplication.home="/home/libiao/flex_sdk_4.5" -jar "/home/libiao/flex_sdk_4.5/lib/fcsh.jar"
 * @author db0@qq.com
 * @version 1.0.1
 * @date 2015-08-28
 */
package
{
	import com.coltware.airxlib.utils.StringLineReader;
	import com.coltware.airxmail.MailParser;
	import com.coltware.airxmail.MimeBodyPart;
	import com.coltware.airxmail.MimeMessage;
	import com.coltware.airxmail.MimeMultiPart;
	import com.coltware.airxmail.pop3.command.POP3Command;
	import com.coltware.airxmail.pop3.POP3Client;
	import com.coltware.airxmail.pop3.POP3ListEvent;
	import com.coltware.airxmail.pop3.POP3Event;
	import com.coltware.airxmail.pop3.POP3MessageEvent;
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.utils.ByteArray;
	import flash.utils.IDataInput;
	import mx.utils.StringUtil;
	
	// (Option) If you use TLSSocket
	import com.hurlant.crypto.tls.TLSSocket;
	
	/**
	 * ...
	 * @author db0@qq.com
	 */
	public class POPTest extends Sprite
	{
		private var container:Sprite = new Sprite();
		
		public function POPTest()
		{
			//var txt:TextField = ViewSet.make_txt(0, 0, ".");
			//addChild(txt);
			
			pop3_sample1();
			//container.mouseChildren = false;
			addChild(container);
			addEventListener(MouseEvent.MOUSE_DOWN, startDrags);
			stage.addEventListener(MouseEvent.MOUSE_UP, startDrags);
		
			//SwfLoader.loadData("a.data", loaded, "binary");
		}
		
		private function loaded(e:Event):void
		{
			if (e && e.type == Event.COMPLETE)
			{
				var _parser:MailParser = new MailParser();
				var bodyEvent:POP3MessageEvent = new POP3MessageEvent(POP3MessageEvent.POP3_MESSAGE);
				bodyEvent.result = _parser.parseStream(e.target.data as ByteArray);
				result_message(bodyEvent);
			}
		}
		
		private function startDrags(e:MouseEvent):void
		{
			switch (e.type)
			{
			case MouseEvent.MOUSE_DOWN: 
				if(container.height>stage.stageHeight)
				container.startDrag(false, new Rectangle(x, 0, 0, 100 - height));
				break;
			case MouseEvent.MOUSE_UP: 
				container.stopDrag();
				break;
			}
		}
		
		private function pop3_sample1():void
		{
			var client:POP3Client = new POP3Client();
			//client.port = 110;  // default port is 110
			//client.host = "pop.163.com";
			//client.setAuth("13054068229@163.com", "db0db0");
			
			// (Option) If you use TLS/SSL
			// you can get as3crypto at http://crypto.hurlant.com/
			client.port = 995;
			client.host = "pop.qq.com";
			client.setAuth("411259349@qq.com", "123456l");
			var tlssocket:TLSSocket = new TLSSocket();
			client.socketObject = tlssocket;
			
			client.addEventListener(POP3ListEvent.POP3_RESULT_UIDL, result_uidl);
			client.addEventListener(POP3Event.POP3_COMMAND_ERROR, Errors);
			client.addEventListener(POP3MessageEvent.POP3_MESSAGE, result_message);
			client.connect();
			client.uidl();
		}
		
		private function result_uidl(e:POP3ListEvent):void
		{
			for (var i:int = 0; i < e.length; i++)
			{
				e.client.retr(e.getNumber(i), e.getValue(i));
			}
			e.client.quit();
		}
		
		private function result_message(e:POP3MessageEvent):void
		{
			var message:MimeMessage = e.getMimeMessage();
			if (message == null) return;
			//trace(e.source);
			var btn:PicBtn = new PicBtn(message, e.source);
			btn.addEventListener(MouseEvent.MOUSE_DOWN, mousedown);
			var r:int = numPic / 3;
			var c:int = numPic % 3;
			btn.x = c * 200;
			btn.y = r * 200;
			container.addChild(btn);
			++numPic;
		
		}
		
		private var stagemouseX:int = 0;
		private var stagemouseY:int = 0;
		
		private function mousedown(e:MouseEvent):void
		{
			var target:PicBtn = e.target as PicBtn;
			switch (e.type)
			{
			case MouseEvent.MOUSE_DOWN: 
				//trace("mouse down");
				target.addEventListener(MouseEvent.MOUSE_UP, mousedown);
				stagemouseX = stage.mouseX;
				stagemouseY = stage.mouseY;
				target.addEventListener(MouseEvent.MOUSE_MOVE, mousedown);
				target.addEventListener(MouseEvent.MOUSE_UP, mousedown);
				break;
			case MouseEvent.MOUSE_MOVE: 
				if (Math.abs(stagemouseX - stage.mouseX) > 3 || Math.abs(stagemouseY - stage.mouseY) > 3)
				{
					target.removeEventListener(MouseEvent.MOUSE_UP, mousedown);
					target.removeEventListener(MouseEvent.MOUSE_MOVE, mousedown);
				}
				break;
			case MouseEvent.MOUSE_UP: 
				target.removeEventListener(MouseEvent.MOUSE_UP, mousedown);
				target.removeEventListener(MouseEvent.MOUSE_MOVE, mousedown);
				//trace("clicked");
				addChild(new PageMain(target.message, target.source));
				break;
				
			}
		}
		
		private var numPic:uint = 0;
		
		private function Errors(e:POP3Event):void
		{
			trace(e.message);
		
			//SwfLoader.loadData("a.data", loaded, "binary");
			var btn:PicBtn = new PicBtn(null, null);
			btn.title.text = e.message;
			var r:int = numPic / 3;
			var c:int = numPic % 3;
			btn.x = c * 200;
			btn.y = r * 200;
			container.addChild(btn);
			++numPic;
		}
	
	}

}
import com.coltware.airxmail.encode.Base64;
import com.coltware.airxmail.MailParser;
import com.coltware.airxmail.MimeBodyPart;
import com.coltware.airxmail.MimeMessage;
import com.coltware.airxmail.MimeMultiPart;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.utils.ByteArray;
import flash.utils.Endian;

class PicBtn extends Sprite
{
	public var message:MimeMessage = null;
	public var source:ByteArray;
	public var title:TextField = new TextField();
	
	public function PicBtn(message:MimeMessage, source:ByteArray)
	{
		mouseChildren = false;
		this.source = source;
		//trace(source);
		addChild(title);
		title.width = 200;
		title.height = 200;
		//title.background = true;
		title.border = true;
		if (message == null) return;
		this.message = message;
		title.text = message.subjectUTF8;
		//trace("主题:", message.subjectUTF8);
		//trace(message.bodyText);
		//trace(message.getDate());
		//trace(message.fromUTF8);
		
		for each (var part:MimeBodyPart in message.partChildren)
		{
			if (part.contentType.getValue().match(/application\/octet-stream/i))
			{
				var partName:String = part.contentType.getValue().replace(/[\r\n]/mg, "").replace(/^.*name="([^"]+)".*$/m, "$1");
				trace("is attachment:", message.attachmentChildren.indexOf(part) >= 0);
				if (partName.match(/(\.png|\.jpeg|\.jpg|\.gif)$/i))
				{
					trace("pic name:", partName);
					part.bodyByteArray.position = 0;
					SwfLoader.loadBytes(part.bodyByteArray, addpic);
					return;
				}
			}
		}
	
	}
	
	private function addpic(e:Event):void
	{
		if (e && e.type == Event.COMPLETE)
		{
			var bmp:Bitmap = e.target.content as Bitmap;
			ViewSet.fullCenter(bmp, 0, 0, 200, 200);
			addChildAt(bmp, 0);
		}
	}

}

import com.hurlant.util.Base64;

class PageMain extends Sprite
{
	
	public var message:MimeMessage = null;
	private var txt:TextField = new TextField();
	private var closeBtn:Sprite = null;
	private var source:ByteArray = null;
	
	public function PageMain(message:MimeMessage, source:ByteArray)
	{
		this.source = source;
		if (message == null)
			return;
		this.message = message;
		if (stage) init(null);
		else addEventListener(Event.ADDED_TO_STAGE, init);
	}
	
	private function init(e:Event):void
	{
		removeEventListener(Event.ADDED_TO_STAGE, init);
		addChildAt(txt, 0);
		if (closeBtn == null)
		{
			closeBtn = new Sprite();
			var closeTxt:TextField = new TextField();
			closeTxt.background = true;
			closeTxt.border = true;
			closeTxt.text = "返回";
			closeTxt.autoSize = "left";
			closeBtn.addChild(closeTxt);
			closeBtn.x = stage.stageWidth - closeBtn.width;
		}
		addChild(closeBtn);
		closeBtn.addEventListener(MouseEvent.CLICK, close);
		txt.background = true;
		txt.wordWrap = true;
		txt.width = stage.stageWidth;
		txt.height = stage.stageHeight;
		txt.text = "主题:" + message.subjectUTF8;
		txt.appendText("\n");
		txt.appendText("来自:" + message.fromUTF8);
		txt.appendText("\n");
		txt.appendText("发送至:" + message.toUTF8);
		txt.appendText("\n");
		txt.appendText("时间:" + message.date);
		txt.appendText("\n");
		txt.appendText("\n");
		txt.appendText(message.bodyText);
		//trace(message.bodyByteArray.length);
		//trace(message.children.length);
		//txt.appendText(source.length.toString());
		curH = txt.textHeight;
		//trace(source.toString().substr(0000,40000));
		/*
		   for each (var attachment:MimeBodyPart in message.attachmentChildren)
		   {
		   //trace(attachment.bodyFormat,attachment.bodyText,attachment.bodyByteArray.length);
		   //trace(attachment.contentType.getValue(), attachment.bodyByteArray.length);
		   if (attachment.contentType.getValue().match(/application\/octet-stream/))
		   {
		   var attachmentName:String = attachment.contentType.getValue().replace(/[\r\n]/mg, "").replace(/^.*name="([^"]+)".*$/m, "$1");
		
		   if (attachmentName.match(/(\.png|\.jpeg|\.jpg|\.gif)$/i))
		   {
		   //trace("name:", attachmentName);
		   SwfLoader.loadBytes(attachment.bodyByteArray, addpic);
		   }
		   }
		   }*/
		//trace(message.bodyFormat, message.bodyType, message.bodyText);
		//trace("attachment:", message.attachmentChildren[0] );
		
		//for each (var part:MimeBodyPart in message.partChildren)
		for each (var part:MimeBodyPart in message.children)
		{
			var partName:String = part.contentType.getValue().replace(/[\r\n]/mg, "").replace(/^.*name="([^"]+)".*$/m, "$1");
			trace("child type::", part.contentType.getValue());
			var deltH:int = curH - txt.textHeight;
			if (message.attachmentChildren.indexOf(part) >= 0)
			{
				//trace("is attachment:" + curH + " " + txt.textHeight + " " + partName);
				txt.appendText("\n");
				txt.appendText("附件:" + partName);
				curH = txt.textHeight + deltH;
			}
			else if (part.contentType.getValue().match(/text\/html/))
			{
				txt.appendText("\n");
				txt.appendText(part.bodyText);
				curH = txt.textHeight + deltH;
				var picArr:Array = part.bodyText.match(/<img [^>]+>/g);
				for each (var _url:String in picArr)
				{
					var url:String = String(_url).replace(/^.*src="([^"]+)".*$/, "$1");
					SwfLoader.SwfLoad(url, addpic);
				}
				trace("picarr:", picArr);
			}
			else if (part.contentType.getValue().match(/text\/plain/))
			{
				deltH = curH - txt.textHeight;
				txt.appendText("\n");
				txt.appendText(part.bodyText);
				curH = txt.textHeight + deltH;
			}
			else if (partName.match(/(\.png|\.jpeg|\.jpg|\.gif)$/i))
			{
				//trace("----------->pic name:", partName, part.bodyByteArray.length);
				if (part.bodyByteArray)
				{
					part.bodyByteArray.position = 0;
					SwfLoader.loadBytes(part.bodyByteArray, addpic);
				}
			}
			else if (part.contentType.getValue().match(/multipart\/alternative/i))
			{
				var boundary:String = part.contentType.getParameter("boundary");
				trace(boundary);
				var sonpartArr:Array = String(source).split("\r\n\r\n--" + boundary);
				trace(sonpartArr.length);
				var i:int = 1;
				while (i < sonpartArr.length)
				{
					var content:String = sonpartArr[i];
					if (content.charAt() == '-') break;
					var arr:Array = content.split("\r\n\r\n");
					if (arr.length > 1)
					{
						var _name:String = String(arr[0]).replace(/[\r\n]/g, "").replace(/^.*name="([^"]+)".*$/m, "$1");
						var charset:String = String(arr[0]).replace(/[\r\n]/g, "").replace(/^.*charset="([^"]+)".*$/m, "$1");
						var ContentType:String = String(arr[0]).replace(/[\r\n]/g, "").replace(/^.*Content-Type: ([^ ;]+);.*$/m, "$1");
						var Encoding:String = String(arr[0]).replace(/[\r\n]/g, "").replace(/^.*Encoding: ([\d\w]+).*$/im, "$1");
						
						var data:String = arr[1];
						if (Encoding.match(/base64/i))
						{
							//var bytes:ByteArray = new ByteArray();
							//bytes.writeMultiByte(com.hurlant.util.Base64.decode(data), charset);
							var bytes:ByteArray = com.hurlant.util.Base64.decodeToByteArray(data.replace(/[\r\n]/mg, ""));
							bytes.endian = Endian.LITTLE_ENDIAN;
							//trace(data);
							if (charset.length != String(arr[0]).length)
							{
								bytes.position = 0;
								data = bytes.readMultiByte(bytes.length, charset);
									//trace(bytes);
									//trace(data);
							}
							else
							{
								data = String(bytes);
							}
							if (ContentType == "text/plain")
							{
								curH = txt.textHeight;
								deltH = curH - txt.textHeight;
								txt.appendText("\n");
								txt.appendText(data);
								curH = txt.textHeight + deltH;
							}
							else if (ContentType == "text/html")
							{
								curH = txt.textHeight;
								deltH = curH - txt.textHeight;
								txt.appendText("\n");
								txt.appendText(data);
								curH = txt.textHeight + deltH;
							}
							else
							{
								
							}
						}
						
						//trace(arr);	
						trace("====", _name);
						trace("====", charset);
						trace("====", ContentType);
						trace("====", Encoding);
							//trace(arr.length);	
					}
					//trace(i, sonpartArr[i]);
					++i;
				}
				trace("=================================");
					//for each (var son:MimeBodyPart in message.findParts("multipart\/alternative")) {
					//for each (var son:MimeMultiPart in MimeMultiPart(part.findParts("multipart\/alternative")).partChildren) 
					//{
					//trace("son bodyType====>", son.contentType.getValue(),"bodyText:",son.bodyText);
					//}
					//var _parser:MailParser = new MailParser();
					//var m:MimeMessage = _parser.parseStream(source.toString().indexOf(part.contentType.getValue()) as ByteArray);
					//result_message(bodyEvent);
					//trace(part.contentType.getValue().match("=\"\"")==null);
			}
			else if (part.contentType.getValue().match(/application\/octet-stream/i))
			{
				
				trace("other binary streem ========");
			}
			else
			{
				trace("bodyType====>", part.contentType.getValue());
			}
				//trace("============start==============");
				//trace(part.bodyText.length);
				//trace(part.getHeaderKyes());
				//trace(part.bodyByteArray.length);
				//trace(part.bodyType);
				//trace(part.contentType.getValue());
				//trace(part.bodyText);
				//trace("============end==============");
		}
	}
	
	private function close(e:MouseEvent):void
	{
		ViewSet.removes(this);
		dispatchEvent(new Event("close__"));
	}
	
	private var curH:int = 0;
	
	private function addpic(e:Event):void
	{
		
		if (e && e.type == Event.COMPLETE)
		{
			var bmp:Bitmap = e.target.content as Bitmap;
			if (bmp)
			{
				trace("add pic" + bmp.height + " " + curH);
				//ViewSet.fullCenter(bmp, 0, 0, 200, 200);
				bmp.y = curH;
				curH += bmp.height;
				addChild(bmp);
			}
		}
	}

}